package com.atguigu.zk.monitorupdown;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.List;

/**
 * 服务提供者
 */
public class ServiceProvider {


    private String connectString = "lc01:2181,lc02:2181,lc03:2181";
    private int sessionTimeOut = 2000;
    private ZooKeeper zooKeeper = null;


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        ServiceProvider serviceProvider = new ServiceProvider();
        // 1 获取zk连接
        serviceProvider.connect();
        // 2 向zk中注册，生成服务节点路径信息
        serviceProvider.register(args[0]);
        // 3 执行服务的业务逻辑
        serviceProvider.business();
    }

    private void business() throws InterruptedException {
        // 延时阻塞，保持线程不会终结
        Thread.sleep(Long.MAX_VALUE);
    }

    private void register(String serverName) throws KeeperException, InterruptedException {
        zooKeeper.create("/servers/"+serverName, serverName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(serverName + "已经上线，在zk集群中注册成功。");
    }

    private void connect() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeOut, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
            }
        });
    }
}
